package com.lakeworks.service.api;

import com.alibaba.fastjson.JSONObject;
import com.lakeworks.common.annotation.MethodHandler;
import com.lakeworks.common.annotation.MethodName;
import com.lakeworks.common.core.domain.AjaxResult;
import com.lakeworks.common.domain.channel.*;
import com.lakeworks.common.domain.channel.ticket.TicketBeforeInfo;
import com.lakeworks.common.domain.channel.ticket.TicketChannel;
import com.lakeworks.common.domain.channel.ticket.TicketFileInfo;
import com.lakeworks.common.domain.channel.ticket.TicketSolveInfo;
import com.lakeworks.common.domain.ticket.TktClaimsRecord;
import com.lakeworks.common.domain.ticket.TktTicketFile;
import com.lakeworks.common.enums.ticket.TicketBackStatus;
import com.lakeworks.common.utils.StringUtils;
import com.lakeworks.domain.CompleteInfo;
import com.lakeworks.domain.SysChannel;
import com.lakeworks.domain.vo.TicketBackVo;
import com.lakeworks.mapper.SysChannelMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Map;
import java.util.stream.Collectors;

import static com.alibaba.fastjson.JSON.parseObject;

@Component
@MethodHandler
public class MerchantAsync{


    @Resource
    private SysChannelMapper sysChannelMapper;

    @Autowired
    private MerchantMap merchantMap;

    private static final Logger log = LoggerFactory.getLogger(MerchantAsync.class);
    /**
     * 入场单状态回写
     */
    public String backPickState(PickUpStatus pickUpStatus, Long channelId) {
        log.info("入场单状态回写---param:[{}],channel:[{}]",pickUpStatus,channelId);
        MerchantApiService service = merchantMap.getService(getChannelCode(channelId));
        if (service != null) {
            String result = service.backPickState(pickUpStatus);
            if(StringUtils.isNotBlank(result)){
                return result;
            }else {
                log.error("入场单状态回写::渠道相应结果出错");
                return "500";
            }
        }
        log.error("入场单状态回写::没有找到具体实现类");
        return "500";
    }

    /**
     * 回写产品信息
     */
    public String backProduct(OprProductInfo productInfo, Long channelId) {
        log.info("回写产品信息---param:[{}],channel:[{}]",productInfo,channelId);
        MerchantApiService service = merchantMap.getService(getChannelCode(channelId));
        if (service != null) {
            String result = service.backProduct(productInfo);
            if(StringUtils.isNotBlank(result)){
                return result;
            }else {
                log.error("回写产品信息::渠道相应结果出错");
                return "500";
            }
        }
        log.error("回写产品信息::没有找到具体实现类");
        return "500";
    }

    /**
     * 回写产品状态
     */
    public String backProductState(ProductStatus productStatus, Long channelId) {
        log.info("回写产品状态---param:[{}],channel:[{}]",productStatus,channelId);
        MerchantApiService service = merchantMap.getService(getChannelCode(channelId));
        if (service != null) {
            String result = service.backProductState(productStatus);
            if(StringUtils.isNotBlank(result)){
                return result;
            }else {
                log.error("回写产品状态::渠道相应结果出错");
                return "500";
            }
        }
        log.error("回写产品状态::没有找到具体实现类");
        return "500";
    }

    /**
     * 回写质检状态
     */
    public String backQualState(QualityResult qualityResult, Long channelId) {
        log.info("回写质检状态---param:[{}],channel:[{}]",qualityResult,channelId);
        MerchantApiService service = merchantMap.getService(getChannelCode(channelId));
        if (service != null) {
            String result = service.backQualState(qualityResult);
            if(StringUtils.isNotBlank(result)){
                return result;
            }else {
                log.error("回写产品信息::渠道相应结果出错");
                return "500";
            }
        }
        log.error("回写产品信息::没有找到具体实现类");
        return "500";
    }

    /**
     * 回写出厂单状态
     */
    public String backShipState(ShipmentStatus shipmentStatus, Long channelId) {
        log.info("回写出厂单状态---param:[{}],channel:[{}]",shipmentStatus,channelId);
        MerchantApiService service = merchantMap.getService(getChannelCode(channelId));
        if (service != null) {
            String result = service.backShipState(shipmentStatus);
            if(StringUtils.isNotBlank(result)){
                return result;
            }else {
                log.error("回写产品信息::渠道相应结果出错");
                return "500";
            }
        }
        log.error("回写产品信息::没有找到具体实现类");
        return "500";
    }




    /**
     * 回写产品格架号
     */
    //@Async
    public String backProductFrameNo(ProductFrame productFrame, Long channelId) {
        log.info("回写产品格架号---param:[{}],channel:[{}]",productFrame,channelId);
        MerchantApiService service = merchantMap.getService(getChannelCode(channelId));
        if (service != null) {
            String result = service.backProductFrameNo(productFrame);
            if(StringUtils.isNotBlank(result)){
                return result;
            }else {
                log.error("回写产品信息::渠道相应结果出错");
                return "500";
            }
        }
        log.error("回写产品信息::没有找到具体实现类");
        return "500";
    }


    public String pushCompleteInfo(CompleteVo completeVo, Long channelId) {
        log.info("回写产品补拍补附件信息---param:[{}],channel:[{}]",completeVo,channelId);
        MerchantApiService service = merchantMap.getService(getChannelCode(channelId));
        if (service != null) {
            String result = service.pushCompleteInfo(completeVo);
            if(StringUtils.isNotBlank(result)){
                return result;
            }else {
                log.error("回写产品信息::渠道相应结果出错");
                return "500";
            }
        }
        log.error("回写产品信息::没有找到具体实现类");
        return "500";
    }



    /**
     * 反馈工单操作选项
     */
  /*  public Map backTicket(TicketBackVo ticketBackVo, Long channelId) {
        MerchantApiService service = merchantMap.getService(getChannelCode(channelId));
        if (service != null) {
            return service.backTicket(ticketBackVo);
        }
        return null;
    }*/


    /**
     * 推送工单信息
     */
    public Map pushTicket(TicketChannel ticketChannel, Long channelId) {
        log.info("推送工单信息---param:[{}],channel:[{}]",ticketChannel,channelId);
        MerchantApiService service = merchantMap.getService(getChannelCode(channelId));
        if (service != null) {
            return service.pushTicket(ticketChannel);
        }
        return null;
    }


   /* @MethodName("method1")
    public AjaxResult pushInfo(TicketBackVo ticketBackVo){
        System.out.println("method1:::"+ticketBackVo.toString());
        return AjaxResult.success();
    }


    @MethodName("method2")
    public AjaxResult push(TicketBackVo ticketBackVo){
        System.out.println("method2:::"+ticketBackVo.toString());
        return AjaxResult.success();
    }*/

    /**
     * 工厂反馈  可以处理
     */
    @MethodName(TicketBackStatus.CANSOLVE)
    public AjaxResult ftyCansolveProcessor(TicketBackVo ticketBackVo) {
        log.info("工厂反馈  可以处理---param:[{}]",ticketBackVo);
        MerchantApiService service = merchantMap.getService(getChannelCode(ticketBackVo.getChannelId()));
        if (service != null) {
            TicketSolveInfo build = TicketSolveInfo.builder()
                    .ticketId(ticketBackVo.getTicketId())
                    .degree(ticketBackVo.getDegree())
                    .comment(ticketBackVo.getRemark())
                    .amount(ticketBackVo.getAmount())
                    .build();
            if(!CollectionUtils.isEmpty(ticketBackVo.getTktTicketFiles())){
                build.setVouchers(ticketBackVo.getTktTicketFiles().stream().map(TktTicketFile::getFileUrl).collect(Collectors.toList()));
            }
            Map map = service.ftyCansolveProcessor(build);
            if(map != null){
                return AjaxResult.success(String.valueOf(map.get("code")),String.valueOf(map.get("body")));
            }

        }
        return null;
    }

    /**
     * 工厂反馈  已处理好
     */
    @MethodName(TicketBackStatus.SOLVEDONE)
    public AjaxResult ftyHandledProcessor(TicketBackVo ticketBackVo) {
        log.info("工厂反馈  已处理好---param:[{}]",ticketBackVo);
        MerchantApiService service = merchantMap.getService(getChannelCode(ticketBackVo.getChannelId()));
        if (service != null) {
            Map map = service.ftyHandledProcessor(getTicketFileInfo(ticketBackVo));
            if(map != null){
                return AjaxResult.success(String.valueOf(map.get("code")),String.valueOf(map.get("body")));
            }
        }
        return null;
    }


    /**
     * 工厂反馈  处理不好
     */
    @MethodName(TicketBackStatus.NOTSOLVE)
    public AjaxResult ftyNohandledProcessor(TicketBackVo ticketBackVo) {
        log.info("工厂反馈  处理不好---param:[{}]",ticketBackVo);
        MerchantApiService service = merchantMap.getService(getChannelCode(ticketBackVo.getChannelId()));
        if (service != null) {
            Map map = service.ftyNohandledProcessor(getTicketFileInfo(ticketBackVo));
            if(map != null){
                return AjaxResult.success(String.valueOf(map.get("code")),String.valueOf(map.get("body")));
            }
        }
        return null;
    }



    /**
     * 工厂反馈  联系不上
     */
    @MethodName(TicketBackStatus.NOTREACHED)
    public AjaxResult unbleToContact(TicketBackVo ticketBackVo) {
        log.info("工厂反馈  联系不上---param:[{}]",ticketBackVo);
        MerchantApiService service = merchantMap.getService(getChannelCode(ticketBackVo.getChannelId()));
        if (service != null) {
            Map map = service.unbleToContact(getTicketFileInfo(ticketBackVo));
            if(map != null){
                return AjaxResult.success(String.valueOf(map.get("code")),String.valueOf(map.get("body")));
            }
        }
        return null;
    }


    /**
     * 工厂反馈  核实不一致
     */
    @MethodName(TicketBackStatus.INCONSISTENCY)
    public AjaxResult ftyInconsistency(TicketBackVo ticketBackVo) {
        log.info("工厂反馈  核实不一致---param:[{}]",ticketBackVo);
        MerchantApiService service = merchantMap.getService(getChannelCode(ticketBackVo.getChannelId()));
        if (service != null) {
            Map map = service.ftyInconsistency(getTicketFileInfo(ticketBackVo));
            if(map != null){
                return AjaxResult.success(String.valueOf(map.get("code")),String.valueOf(map.get("body")));
            }
        }
        return null;
    }



    /**
     * 工厂反馈  洗前沟通
     */
    @MethodName(TicketBackStatus.BEFOREWASH)
    public AjaxResult ftyBeforeWash(TicketBackVo ticketBackVo) {
        log.info("工厂反馈  洗前沟通---param:[{}]",ticketBackVo);
        MerchantApiService service = merchantMap.getService(getChannelCode(ticketBackVo.getChannelId()));
        if (service != null) {
            TicketBeforeInfo build = TicketBeforeInfo.builder()
                    .operator(ticketBackVo.getOperator())
                    .ticketId(ticketBackVo.getTicketId())
                    .barcodeVos(ticketBackVo.getBarcodeVos())
                    .comment(ticketBackVo.getRemark())
                    .build();
            if(!CollectionUtils.isEmpty(ticketBackVo.getTktTicketFiles())){
                build.setVouchers(ticketBackVo.getTktTicketFiles().stream().map(TktTicketFile::getFileUrl).collect(Collectors.toList()));
            }
            Map map = service.ftyBeforeWash(build);
            if(map != null){
                return AjaxResult.success(String.valueOf(map.get("code")),String.valueOf(map.get("body")));
            }
        }
        return null;
    }


    /**
     * 工厂反馈  已知悉
     */
    @MethodName(TicketBackStatus.HAVEKNOWN)
    public AjaxResult ftyHaveKnown(TicketBackVo ticketBackVo) {
        log.info("工厂反馈  已知悉---param:[{}]",ticketBackVo);
        MerchantApiService service = merchantMap.getService(getChannelCode(ticketBackVo.getChannelId()));
        if (service != null) {
            Map map = service.ftyHaveKnown(getTicketFileInfo(ticketBackVo));
            if(map != null){
                return AjaxResult.success(String.valueOf(map.get("code")),String.valueOf(map.get("body")));
            }
        }
        return null;
    }


    /**
     * 工厂反馈  反馈
     */
    @MethodName(TicketBackStatus.FEEDBACK)
    public AjaxResult ftyFeedback(TicketBackVo ticketBackVo) {
        log.info("工厂反馈  反馈---param:[{}]",ticketBackVo);
        MerchantApiService service = merchantMap.getService(getChannelCode(ticketBackVo.getChannelId()));
        if (service != null) {
            Map map = service.ftyFeedback(getTicketFileInfo(ticketBackVo));
            if(map != null){
                return AjaxResult.success(String.valueOf(map.get("code")),String.valueOf(map.get("body")));
            }
        }
        return null;
    }

    /**
     * 工厂反馈  上传资料
     */
    @MethodName(TicketBackStatus.UPLOADDATA)
    public AjaxResult uploaddataProcessor(TicketBackVo ticketBackVo) {
        log.info("工厂反馈  上传资料---param:[{}]",ticketBackVo);
        MerchantApiService service = merchantMap.getService(getChannelCode(ticketBackVo.getChannelId()));
        if (service != null) {
            Map map = service.uploaddataProcessor(getTicketFileInfo(ticketBackVo));
            if(map != null){
                return AjaxResult.success(String.valueOf(map.get("code")),String.valueOf(map.get("body")));
            }
        }
        return null;
    }

    /**
     * 工厂反馈  更新工单
     */
    public AjaxResult ticketUpdate(TicketBackVo ticketBackVo) {
        log.info("工厂反馈  更新工单---param:[{}]",ticketBackVo);
        MerchantApiService service = merchantMap.getService(getChannelCode(ticketBackVo.getChannelId()));
        if (service != null) {
            Map map = service.ticketUpdate(getTicketFileInfo(ticketBackVo));
            if(map != null){
                return AjaxResult.success(String.valueOf(map.get("code")),String.valueOf(map.get("body")));
            }
        }
        return null;
    }



    /**
     * 获取订单信息
     */
    public String getOrderInfo(String orderNo,Long channelId){
        log.info("获取订单信息---param:[{}],channelId:[{}]",orderNo,channelId);
        MerchantApiService service = merchantMap.getService(getChannelCode(channelId));
        if (service != null) {
            return service.getOrderInfo(orderNo);
        }
        return null;
    }


    public String getOrderDetails(String orderNo,Long channelId){
        log.info("获取订单详情---param:[{}],channelId:[{}]",orderNo,channelId);
        MerchantApiService service = merchantMap.getService(getChannelCode(channelId));
        if (service != null) {
            return service.getOrderDetails(orderNo);
        }
        return null;
    }



    public String getOrderExpress(String expressNo,Long channelId){
        log.info("获取订单详情---param:[{}],channelId:[{}]",expressNo,channelId);
        MerchantApiService service = merchantMap.getService(getChannelCode(channelId));
        if (service != null) {
            return service.getOrderExpress(expressNo);
        }
        return null;
    }



    /**
     * 请求平台判断出厂单是否可以出厂
     * @return
     */
    public Boolean isLeave(String orderNo,Long channelId){
        log.info("出厂单是否可以出厂---param:[{}],channelId:[{}]",orderNo,channelId);
        MerchantApiService service = merchantMap.getService(getChannelCode(channelId));
        if (service != null) {
            String result = service.isLeave(orderNo);
            if(StringUtils.isNotBlank(result)){
                JSONObject jsonObject = parseObject(result);
                String flag = jsonObject.getString("flag");
                if(flag.equals("true")){
                    return true;
                }
            }
        }
        return false;
    }




    /**
     * 工厂发起复议
     * @return
     */
    public String reconsider(TktClaimsRecord tktClaimsRecord, Long channelId){
        log.info("工厂发起复议---param:[{}],channelId:[{}]",tktClaimsRecord.toString(),channelId);
        MerchantApiService service = merchantMap.getService(getChannelCode(channelId));
        if (service != null) {
            return service.reconsider(tktClaimsRecord);
        }
        return null;
    }





    private TicketFileInfo getTicketFileInfo(TicketBackVo ticketBackVo){
        TicketFileInfo build = TicketFileInfo.builder().operator(ticketBackVo.getOperator()).ticketId(ticketBackVo.getTicketId()).comment(ticketBackVo.getRemark()).build();
        if(!CollectionUtils.isEmpty(ticketBackVo.getTktTicketFiles())){
            build.setVouchers(ticketBackVo.getTktTicketFiles().stream().map(TktTicketFile::getFileUrl).collect(Collectors.toList()));
        }
        return build;
    }


    private String getChannelCode(Long channelId) {
        SysChannel channel = sysChannelMapper.selectSysChannelById(channelId);
        if(channel == null){
            throw new RuntimeException("渠道信息错误！");
        }
        return channel.getCode();
    }


}
